﻿using System;
using System.Data;
using GameOn.Web.Entities;

namespace GameOn.Web.Services
{
    /// <summary>
    /// A service for registering and editing players
    /// </summary>
    public class PlayerRegistrationService : IPlayerRegistrationService
    {
        private GameOnEntities Entities { get; set; }

        public PlayerRegistrationService(GameOnEntities entities)
        {
            Entities = entities;
        }

        /// <summary>
        /// Adds a Player, returning the new ID
        /// </summary>
        /// <param name="player">A Player DTO</param>
        public int AddPlayer(Player player)
        {
            if (player.Id != 0) throw new InvalidOperationException("Don't use the AddPlayer method to update a player. Use EditPlayer instead");
            Entities.CreateObjectSet<Player>().AddObject(player);
            var rankHistory = new RankHistory {Player = player, Rank = player.CurrentRank, RankDate = DateTime.Now};
            Entities.CreateObjectSet<RankHistory>().AddObject(rankHistory);
            Entities.SaveChanges();
            return player.Id;
        }
    }
}
